<?php
/**
 * Created by PhpStorm.
 * User: leishaofa
 * Date: 2017/7/16
 * Time: 11:09
 * parame:脚本调用接口
 */
class RpcAction extends Action
{
    public function __construct()
    {
        parent::__construct();
        if ( strpos($_SERVER['HTTP_USER_AGENT'],'FLASHSALE') === false ) {
            return  $this->ajaxReturn(array('code' => 4004, 'msg' => "成功", 'data' => ''));
        }
        if(!IS_AJAX){
            return $this->ajaxReturn(array('code'=>4003,'msg'=>'成功','data'=>''));
        }
    }

    /**
     *test 测试调用
     */
    public function getsite()
    {
        $pythonshell="soup=BeautifulSoup(spHtml.text,'html.parser')
    script=soup.select('script')[-4]
    productid=str(script).split(',')[2].split('+')[1]
    #print productid
    infoUrl='http://www.adidas.com.cn/specific/product/ajaxview/?id='+productid
    infoHml=requests.get(infoUrl,headers=loginHead)

    infosoup=BeautifulSoup(infoHml.text,'html.parser')
    #sizetext=infosoup.select('#size_box')[0].text

    option=infosoup.select('#size_box option')
    sizeVal=[]
    sizetext=[]
    for tag in option:
        sizeVal.append(tag['value'])
        sizetext.append(tag.text)
        #print tag['value']
    return {\"allSize\":(sizetext,sizeVal)}";
        exec('python '.dirname(dirname(dirname(dirname(dirname(__FILE__))))).'\python2\getSize.py http://www.adidas.com.cn/cg4226 '.$pythonshell,$array,$ret);

        var_dump($ret);
        var_dump($array);
    }

    /**
     * 拉取计划任务
     *$tid 团队标识
     *$type  1：注册任务 2：抢购任务
     *
     */
    public function planTask(){
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:'';
        $type=is_numeric($_POST['type'])?$_POST['type']:'';
        
        if(empty($tid)){
             return $this->ajaxReturn(array('code' => 4002, 'msg' => "参数不正确", 'data' => ''));
        }
        $model=M('','',C('flashSale'));
        if($type ==2) {
            $where=' where a.status = 4 && a.task_type = 2 && b.task_status =1 && a.t_id='.$tid.' ';
            $sqlcount = "select a.*,b.task_url,b.goods_time,b.pinicBuying_types from f_task_rel as a left join f_task as b ON a.task_id=b.task_id and a.site_id=b.site_id " . $where . "  ORDER BY rand() LIMIT 1";
            $result=$model->query($sqlcount);
        }elseif ($type ==1){
           /* $where=' where a.status = 4 && a.task_type = 1 && b.site_status=1 && a.t_id='.$tid.' ';
            $sqlcount = "select a.*,b.site_name,d.t_name from f_task_rel as a  left join f_site as b on a.site_id=b.site_id  LEFT JOIN f_team AS d ON a.t_id = d.t_id " . $where . "  ORDER BY rand() LIMIT 1";
            $result=$model->query($sqlcount);*/
        }
        if(isset($result) && !empty($result) && is_array($result)) {
            return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' => ''));
        }
    }

    /**
     * 拉取用户注册数据
     * $tid团队id
     * $stid 站点id
     */
   /* public function redisteruser(){
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $siteid=is_numeric($_POST['stid'])?$_POST['stid']:0;
        if($tid && $siteid){
            $model = M('', '', C('flashSale'));//SELECT * FROM users WHERE find_in_set('aa@email.com', emails);
            $where="where a.t_id = ".$tid." && (CONCAT(',', a.u_site_no, ',') NOT LIKE '%,".$siteid.",%' || a.u_site_no IS NULL) && (CONCAT(',', a.u_site_ok, ',') NOT LIKE '%,".$siteid.",%' || a.u_site_ok is null)";
            $sqlcount = "select *,b.defaultpwd from f_user as a left join f_team as b ON a.t_id = b.t_id " . $where . " ORDER BY rand() limit 1 ";
            $result = $model->query($sqlcount);
            /!* $result=array_map(function($v){
                 $v['u_site_no']=empty($v['u_site_no'])?'':explode(',',$v['u_site_no']);
                 $v['u_site_ok']=empty($v['u_site_ok'])?'':explode(',',$v['u_site_ok']);
                 $v['u_field']=json_decode($v['u_field'],true);
                 $v['u_address']= $v['u_field']['addressremark']['country'].$v['u_field']['addressremark']['province'].$v['u_field']['addressremark']['city'].$v['u_field']['addressremark']['district'].$v['u_address'];
                 $v['u_field']='';
                 return $v;
             },$result);*!/
            if(isset($result) && is_array($result) && !empty($result)) {
                $result=$result[0];
                $result=empty($result['u_pwd'])?$result['defaultpwd']:$result['u_pwd'];
                $result['u_site_no']=empty($result['u_site_no'])?'':explode(',',$result['u_site_no']);
                $result['u_site_ok']=empty($result['u_site_ok'])?'':explode(',',$result['u_site_ok']);
                $result['u_field']=json_decode($result['u_field'],true);
                $result['site_id']=$siteid;
                $result['u_addressremark']=$result['u_field']['addressremark']['street'].$result['u_field']['addressremark']['sematic_description'];
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' => ''));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "参数类型错误", 'data' => ''));
        }
    }*/

    /**
     * 用户注册回调接口
     * $uid 用户id
     * $tid 团队id
     * $siteid  站点id
     * $type 类型 1：失败 2：成功
     */
   /* public function registerRollback(){
        $uid=is_numeric($_POST['uid'])?$_POST['uid']:0;
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $siteid=is_numeric($_POST['stid'])?$_POST['stid']:0;
        $type=is_numeric($_POST['type'])?$_POST['type']:0;
        if($uid && $tid){
            $model = M('', '', C('flashSale'));
            /!* $querysql="select u_id,u_site_no,u_site_ok from f_user where u_id=".$uid." and t_id = ".$tid." ";
             $queryresult=$model->query($querysql);
             $queryresult=$queryresult[0];*!/
            if($type ==1){
                $sql="update f_user set u_site_no=CONCAT_WS(',',u_site_no,".$siteid.") where u_id=".$uid." and t_id = ".$tid." ";
            }elseif($type ==2){
                $sql="update f_user set u_site_ok=CONCAT_WS(',',u_site_ok,".$siteid.") where u_id=".$uid." and t_id = ".$tid." ";
            }
            $result=$model->execute($sql);
            if(isset($result) && $result) {
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' =>$sql));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "参数类型错误", 'data' => ''));
        }
    }*/

    /**
     *任务用户接口
     * $taskrelid 任务id
     * $tid 团队id
     */
    public function taskuser(){
        $taskrelid=is_numeric($_POST['taskrelid'])?$_POST['taskrelid']:0;
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $type=empty($_POST['type'])?0:$_POST['type'];
        if($taskrelid && $tid){
            $model = M('', '', C('flashSale'));
            $where=" and a.t_id = ".$tid." and  a.u_status = 1";

            $sitesql= "select site_id from f_task_rel where task_relid = '".$taskrelid."'";
            $resultsite=$model->query($sitesql);
            if(empty($resultsite)){
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有查询到该任务", 'data' =>''));
            }else {
                $where .= " and a.u_site_ok like '%" . $resultsite[0]['site_id'] . "%' ";
            }
            $orderbyarray=array('ORDER BY a.mobile asc','ORDER BY a.mobile desc','ORDER BY a.u_id asc','ORDER BY a.u_id desc','ORDER BY a.create_time asc','ORDER BY a.create_time desc');
            $orderby=$orderbyarray[array_rand($orderbyarray,1)];
            //老的数据库设计
          //  $sqluser = "SELECT a.*,b.defaultpwd FROM f_user AS a LEFT JOIN f_team AS b ON a.t_id = b.t_id WHERE ( SELECT count(1) AS num from  f_order AS c WHERE c.u_id = a.u_id AND c.team_id = a.t_id  AND c.taskrel_id = ".$taskrelid.") = 0 ".$where." order by u_id limit 1";
            //$result = $model->query($sqluser);
            if($type==1){
                $sqluser = "select a.*,d.*,e.* from f_user as a inner join f_user_rel as d on a.u_id=d.u_id inner join f_user_remark as e on e.u_id=a.u_id  where a.t_id = " . $tid . " and d.site_id = " . $resultsite[0]['site_id'] . " AND d.u_site_status = 1 AND d.u_site_task_status = 1 and 
( SELECT count(1) AS num from f_order AS c WHERE c.u_id = a.u_id AND c.team_id = a.t_id  AND c.taskrel_id = " . $taskrelid . ") = 0 " . $orderby . " limit 1";
            }else {

                $sqluser = "select a.*,d.* from f_user as a inner join f_user_rel as d on a.u_id=d.u_id where a.t_id = " . $tid . " and d.site_id = " . $resultsite[0]['site_id'] . " AND d.u_site_status = 1 AND d.u_site_task_status = 1 and 
( SELECT count(1) AS num from f_order AS c WHERE c.u_id = a.u_id AND c.team_id = a.t_id  AND c.taskrel_id = " . $taskrelid . ") = 0 " . $orderby . " limit 1";
            }
           /* $result = $model->query($sqluser);
            print_r($sqluser);

            print_r($result);
            print_r($sqlusers);*/
            $result=$model->query($sqluser);

            if(isset($result) && is_array($result) && !empty($result)) {
                $result=$result[0];
                $model->execute("update f_user_rel set u_site_task_status=2 where u_id='".$result['u_id']."' and u_site_status=1 and site_id='".$resultsite[0]['site_id']."'");
                $result['u_field']=json_decode($result['u_field'],true);
                $result['u_address']=str_replace(array("（","）","(",")"), '', $result['u_address']);
                $result['u_addressremark']=$result['u_field']['addressremark']['street'].$result['u_field']['addressremark']['sematic_description'];
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result,'sql'=>$model->getLastSql()));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' => '','sql'=>$model->getLastSql()));
            }
        }
        return $this->ajaxReturn(array('code' => 4001, 'msg' => "请求失败", 'data' =>''));
    }


    /**
     * 获取已经锁定的用户
    */
    public function taskuser_bank(){
        $taskrelid=is_numeric($_POST['taskrelid'])?$_POST['taskrelid']:0;
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        if($taskrelid && $tid){
            $model = M('', '', C('flashSale'));
            $where=" and a.t_id = ".$tid." and  a.u_status = 1";

            $sitesql= "select site_id from f_task_rel where task_relid = '".$taskrelid."'";
            $resultsite=$model->query($sitesql);
            if(empty($resultsite)){
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有查询到该任务", 'data' =>''));
            }else {
                $where .= " and a.u_site_ok like '%" . $resultsite[0]['site_id'] . "%' ";
            }

            //老的数据库设计
            //  $sqluser = "SELECT a.*,b.defaultpwd FROM f_user AS a LEFT JOIN f_team AS b ON a.t_id = b.t_id WHERE ( SELECT count(1) AS num from  f_order AS c WHERE c.u_id = a.u_id AND c.team_id = a.t_id  AND c.taskrel_id = ".$taskrelid.") = 0 ".$where." order by u_id limit 1";
            //$result = $model->query($sqluser);

            $sqluser="select d.*,a.* from f_user as a inner join f_user_rel as d on a.u_id=d.u_id where a.t_id = ".$tid." and d.site_id = " . $resultsite[0]['site_id'] . " AND d.u_site_status = 1 AND d.u_site_task_status = 2 limit 1";

            /* $result = $model->query($sqluser);
             print_r($sqluser);

             print_r($result);
             print_r($sqlusers);*/
            $result=$model->query($sqluser);

            if(isset($result) && is_array($result) && !empty($result)) {
                $result=$result[0];
                $model->execute("update f_user_rel set u_site_task_status=1 where u_id='".$result['u_id']."' and u_site_status=1 and site_id='".$resultsite[0]['site_id']."'");
                $result['u_field']=json_decode($result['u_field'],true);
                $result['u_address']=str_replace(array("（","）","(",")"), '', $result['u_address']);
                $result['u_addressremark']=$result['u_field']['addressremark']['street'].$result['u_field']['addressremark']['sematic_description'];
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
               // return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' => ''));
            }
        }
        return $this->ajaxReturn(array('code' => 4001, 'msg' => "请求失败", 'data' =>''));
    }


    /**
     *任务用户释放接口
     * $tid 团队id
     * $uid 用户uid
     */
    public function releaseUser(){
        $stid=is_numeric($_POST['stid'])?$_POST['stid']:0;
        $uid=is_numeric($_POST['uid'])?$_POST['uid']:0;
        $model = M('', '', C('flashSale'));
        if($uid && $stid){
            $sql="update f_user_rel set u_site_task_status=1 where u_id='".$uid."' and site_id = '".$stid."' and u_site_task_status=2";
            $updateresult=$model->execute($sql);
            if($updateresult){
                return $this->ajaxReturn(array('code' => 1, 'msg' => "用户释放成功", 'data' => ''));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "用户释放失败", 'data' =>''));
            }
        }
    }


    /**
     * 任务结束回调接口
     * $type 任务类型  1:注册任务 2：抢购任务
     * $taskrelid 任务id
     * $tid 团队id
     * $is_able
     * $msg 短消息内容
     */
    /*public function stoptask(){
        $taskrelid=is_numeric($_POST['taskrelid'])?$_POST['taskrelid']:0;
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $type=is_numeric($_POST['type'])?$_POST['type']:0;
        $isable=is_numeric($_POST['is_able'])?$_POST['is_able']:0;
        $msssg=htmlspecialchars($_POST['msg']);
        $model = M('', '', C('flashSale'));
        if($taskrelid){
            $querysql="select * from f_task_rel WHERE task_relid = ".$taskrelid." and t_id=".$tid."  ";
            $queryresult=$model->query($querysql);
            //第三方网站已下架
            if($isable){
                $sql="UPDATE f_task SET task_status = '3' WHERE task_id = ".$queryresult[0]['task_id']." ";
                $model->execute($sql);
            }
            if($type==1) {
                $sql="delete * from f_task_rel where task_relid = ".$taskrelid." and t_id=".$tid." ";
                $result=$model->execute($sql);
                if(isset($result) && $result ==1) {
                    $msg="您在".$queryresult[0]['createtime']."执行的注册任务在".date('Y-m-d H:i:s')."执行完毕";
                    $insertvalues = "('".$msg."','')";

                    $insertsql = "insert into f_message (t_msg,t_remark) values " . $insertvalues . "; ";
                    $usermodel = M('message', 'f_', C('flashSale'))->execute($insertsql);
                    return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
                }else{
                    return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' =>''));
                }
            }elseif($type ==2){
                $sql="UPDATE f_task_rel SET status = '2' WHERE task_relid = ".$taskrelid." and t_id=".$tid." ";
                $result=$model->execute($sql);
                if(isset($result) && $result ==1) {
                    $msg="您在".$queryresult[0]['createtime']."执行的抢购任务在".date('Y-m-d H:i:s')."执行完毕结束原因：".$msssg;
                    $insertvalues = "('".$msg."','".json_encode($querysql[0])."')";
                    $insertsql = "insert into f_message (t_id,t_msg,t_remark) values " . $insertvalues . "; ";
                    $usermodel = M('message', 'f_', C('flashSale'))->execute($insertsql);
                    return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
                }else{
                    return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' =>''));
                }
            }
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "请求失败", 'data' =>''));
        }
    }*/

    /**
     * 订单记录调用接口
     */
    public function createSignOrder(){
         $model = M('', '', C('flashSale'));
        $postdata=$_POST;
        if(is_numeric($postdata['taskrelid']) && is_numeric($postdata['t_id']) && is_numeric($postdata['u_id'])){
            $usersql="select u_eamil,u_pwd,mobile,u_city,u_address,firstname,u_addresscode from f_user where t_id='".$postdata['t_id']."'  and u_id = '".$postdata['u_id']."'";

            $userresult=$model->query($usersql);

            $postdata['payType']=!empty($postdata['payType'])?$postdata['payType']:"alipay";
            $insertvalues = '('.$postdata['u_id'].','.$postdata['t_id'].','.$postdata['taskrelid'].',"'.$postdata['sptitle'].'","'.$postdata['qty'].'","'.$postdata['payurl'].'","'.$postdata['spPrice'].'",'.$postdata['stid'].',"'.$postdata['yunFei'].'","'.$postdata['payType'].'","'.$postdata['total'].'","'.$postdata['orderNumber'].'",'.json_encode($postdata['goods_attribute'],JSON_UNESCAPED_UNICODE).',"'.$postdata['time'].'")';

            $insertsql = "insert into f_order (u_id,team_id,taskrel_id,order_name,order_num,order_url,goods_countprice,site_id,postage,pay_type,order_price,thirdorderid,remark,ordertime,userremark) values " . $insertvalues . "; ";

            $usermodel =$model->execute($insertsql);
            

            if ($usermodel) {
                $this->ajaxReturn(array('code' => 1, 'msg' => "订单记录成功", 'data' => ''));
            } else {
                $this->ajaxReturn(array('code' =>4001, 'msg' => "订单记录失败", 'data' => ''));
            }
        }
        $this->ajaxReturn(array('code' =>4001, 'msg' => "订单记录失败！", 'data' => ''));

    }

    /**
     * 获取任务状态
     * $taskrelid 任务id
     * $tid 团队id
    */
    public  function getTaskStatus(){
        $taskrelid=is_numeric($_POST['taskrelid'])?$_POST['taskrelid']:0;
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        if($taskrelid && $tid){
            $model = M('', '', C('flashSale'));
                $sql="select status from f_task_rel WHERE task_relid = ".$taskrelid." and t_id=".$tid." ";
                $result=$model->query($sql);
            if ($result) {
                $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result[0]));
            } else {
                $this->ajaxReturn(array('code' =>4001, 'msg' => "获取任务状态失败", 'data' => ''));
            }
        }
         $this->ajaxReturn(array('code' =>4001, 'msg' => "获取任务状态失败", 'data' => ''));
    }

    /**
     * 修改任务状态
     * $taskrelid 任务id
     * $tid 团队id
     */
    public  function upTaskStatus(){
        $taskrelid=is_numeric($_POST['taskrelid'])?$_POST['taskrelid']:0;
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        if($taskrelid){
            $model = M('', '', C('flashSale'));
            $sql="UPDATE f_task_rel SET status = '4' WHERE task_relid = ".$taskrelid." and t_id=".$tid." ";
            $result=$model->execute($sql);
            if ($result) {
                $this->ajaxReturn(array('code' => 1, 'msg' => "任务正在执行中", 'data' => ''));
            } else {
                $this->ajaxReturn(array('code' =>4001, 'msg' => "失败", 'data' => ''));
            }
        }
        $this->ajaxReturn(array('code' =>4001, 'msg' => "失败", 'data' => ''));
    }

   /**
    *新的获取用户注册任务
   */
   public function getRegisterTask(){
       $tid=is_numeric($_POST['tid'])?$_POST['tid']:'';
       $type=is_numeric($_POST['type'])?$_POST['type']:'';

       if(empty($tid)){
           return $this->ajaxReturn(array('code' => 4002, 'msg' => "参数不正确", 'data' => ''));
       }
       $model=M('','',C('flashSale'));
       if ($type == 1){
            $where=' where a.status = 4 && a.task_type = 1 && a.t_id='.$tid.' ';
            $sqlcount = "select a.*,d.t_name from f_task_rel as a  LEFT JOIN f_team AS d ON a.t_id = d.t_id " . $where . "  ORDER BY rand() LIMIT 1";
            $result=$model->query($sqlcount);
            if(!empty($result)){
                $result[0]['rules']=explode(',',$result[0]['rules']);
            }
       }
       if(isset($result) && is_array($result)) {
           return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
       }else{
           return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' => ''));
       }
   }

    /**
     * 新的用户注册任务回调接口
     */
    public function getRegisterTaskBack(){
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $taskrelid=is_numeric($_POST['taskrelid'])?$_POST['taskrelid']:0;
        if($taskrelid && $tid){
            $model = M('', '', C('flashSale'));
            $sql="delete from f_task_rel where task_type = 1 and task_relid = '".$taskrelid."'";
            $result=$model->execute($sql);
            if($result) {
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "失败", 'data' =>$sql));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "参数类型错误", 'data' => ''));
        }
    }

    /**
     * 新的拉取用户注册数据
    */
    public function getRegisterTaskUser(){
        $t_id=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $siteid=is_numeric($_POST['siteid'])?$_POST['siteid']:0;
        $type =empty($_POST['type'])?0:$_POST['type'];
        if($t_id && $siteid){
            $model = M('', '', C('flashSale'));
           // $sqluser = "select * from f_user where t_id = ".$t_id." and u_status =1 and (u_site_ok is null or u_site_no is null or NOT( u_site_ok like '%".$siteid."%' and u_site_no like '%".$siteid."%')) limit 1";
          //  $sqluser = "SELECT * FROM f_user WHERE t_id = ".$t_id."  AND u_status = 1 AND (u_site_ok NOT like '%".$siteid."%' or u_site_ok is null) AND (u_site_no NOT like '%".$siteid."%' or u_site_no is null) LIMIT 1";
            if($type == 1) {
                $cardsql="select remark_id,u_card_id,u_card_name,u_privace as card_privace,u_city as card_city,district as card_district from f_user_remark where u_id = 0 and re_status = 0 and t_id = " . $t_id . " limit 1";
                $resultcard=$model->query($cardsql);
            }
            $sqluser = "select users.* from f_user users  where users.t_id = " . $t_id . " and not exists ( select 1 from f_user_rel rel where rel.u_id = users.u_id and rel.site_id=" . $siteid . " limit 1)  LIMIT 1";
            $resultuser=$model->query($sqluser);
            if($type == 1) {
                if(empty($resultuser) || empty($resultcard)){
                    return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有可注册该平台用户或者没有可用的身份证", 'data' => ''));
                }else{
                    $updatesql="UPDATE f_user_remark SET re_status = '1' WHERE remark_id = '".$resultcard[0]['remark_id']."'";
                    $model->query($updatesql);
                    $resultuser[0]=array_merge($resultuser[0],$resultcard[0]);
                }
            }
            if(!empty($resultuser)){
                $resultuser=$resultuser[0];
                $issetUserRel=$model->execute("select u_id f_user_rel where u_id='".$resultuser['u_id']."' and site_id='".$siteid."'");
                if(empty($issetUserRel)){
                    $model->execute( "insert into f_user_rel (u_id,site_id,u_site_status,u_site_task_status) values ('".$resultuser['u_id']."','".$siteid."','0','1'); ");
                }
                $resultuser['u_field']=json_decode($resultuser['u_field'],true);
                $resultuser['u_address']=str_replace(array("（","）","(",")"), '', $resultuser['u_address']);
                $resultuser['u_addressremark']=$resultuser['u_field']['addressremark']['street'].$resultuser['u_field']['addressremark']['sematic_description'];
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $resultuser));
            }else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有可注册该平台用户", 'data' => ''));
            }

        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "参数错误", 'data' => ''));
        }
    }
    /**
     * 新的用户注册任务用户回调接口
     * {'tid': '7', 'status': '1', 'siteid': u'4', 'uid': u'18490'}
    */
    public function getRegisterTaskUserBack(){
        $uid=is_numeric($_POST['uid'])?$_POST['uid']:0;
        $t_id=is_numeric($_POST['tid'])?$_POST['tid']:0;
        $siteid=is_numeric($_POST['siteid'])?$_POST['siteid']:0;
        $status=is_numeric($_POST['status'])?$_POST['status']:0;
        $remark_id=is_numeric($_POST['remarkId'])?$_POST['remarkId']:0;

        if(!empty($t_id) && !empty($siteid) && !empty($uid)){
            $model = M('', '', C('flashSale'));
            $sqluser="select u_site_status from f_user_rel where u_id = ".$uid." and site_id = ".$siteid." ";
           // $sqluser = "select * from f_user where t_id = ".$t_id." and u_id =".$uid." and ( u_site_ok like '%".$siteid."%' or u_site_no like '%".$siteid."%')";
            $resultuser=$model->query($sqluser);
            if(!empty($resultuser)){
                if(!empty($remark_id)){
                    $sqluser="select remark_id from f_user_remark where remark_id ='".$remark_id."' and t_id ='".$t_id."' ";
                    $isremark=$model->query($sqluser);
                    if(empty($isremark)){
                        return $this->ajaxReturn(array('code' => 4001, 'msg' => "身份证号标识码错误", 'data' => ''));
                    }
                }
                if($status){
                    //身份证号码绑定用户
                    if(!empty($remark_id)){
                        $remarkupdatesql="UPDATE f_user_remark SET re_status = '0' ,u_id='".$uid."' WHERE remark_id = '".$remark_id."'";
                        $model->query($remarkupdatesql);
                    }
                    //修改用户站点注册状态
                    $updatesql="UPDATE f_user_rel SET u_site_status = '1' WHERE u_id = '".$uid."' and site_id = '".$siteid."'";
                }elseif($resultuser[0]['u_site_status'] != 1){
                    //注册失败，释放身份证号码
                    if(!empty($remark_id)){
                        $remarkupdatesql="UPDATE f_user_remark SET re_status = '0' WHERE remark_id = '".$remark_id."'";
                        $model->query($remarkupdatesql);
                    }
                    //修改用户站点注册状态
                    $updatesql="UPDATE f_user_rel SET u_site_status = '2' WHERE u_id = '".$uid."' and site_id = '".$siteid."'";
                   // $updatesql="UPDATE f_user SET u_site_no = '".$oksiteid."' WHERE u_id = '".$uid."' and t_id = '".$t_id."'";
                }
                if($model->execute($updatesql))
                    return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => ''));
                else
                    return $this->ajaxReturn(array('code' => 4001, 'msg' => "记录该平台状态失败", 'data' => ''));
            }else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "该账号错误", 'data' => ''));
            }

        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "参数错误", 'data' => ''));
        }
    }

    /**
     * 获取未开始的抢购商品任务
    */
    public function startTaskRel(){
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:0;
        if(!empty($tid)){
            $model = M('', '', C('flashSale'));
            $sql="select a.*,b.task_status,b.task_url,c.site_name,c.site_status,d.t_name from f_task_rel as a left join f_task as b ON a.task_id=b.task_id and a.site_id=b.site_id left join f_site as c on a.site_id=c.site_id  LEFT JOIN f_team AS d ON a.t_id = d.t_id where a.t_id=".$tid." and a.task_type = 2 and a.status = 1";
            $result=$model->query($sql);
            if(isset($result[0]) && !empty($result[0])){
                return $this->ajaxReturn(array('code' => 1, 'msg' => "成功", 'data' => $result));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "还没有任务", 'data' => ''));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有获取到团队标示", 'data' =>''));
        }
    }

    /**
     * 更具时间匹配左右时间相差不到5分钟固定类型任务
    */
    public function timeTaskMatching(){
        $time=strtotime($_POST['tasktime'])!== false?$_POST['tasktime']:'';
        $tasktype=htmlspecialchars($_POST['tasktype']);
        if($time){
            $model = M('', '', C('flashSale'));
            $sql="select task_relid,status,task_type,createtime from f_task_rel where task_type = '3' and rules like '%\"python\":\"".$tasktype."\"%' and createtime  between '".date('Y-m-d H:i:s',strtotime($time)-5*60)."' and '".date('Y-m-d H:i:s',strtotime($time)+5*60)."' ";
            $result=$model->query($sql);
            if($result){
                return $this->ajaxReturn(array('code' => 1, 'msg' => "时间错误", 'data' =>$result[0]));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "时间错误", 'data' =>''));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "时间错误", 'data' =>''));
        }
    }

    /**
     * 把某一个站点下面某个用户标注为失效
     * @parame $u_id  用户id
     * @parame $t_id 团队id
     * @parame $siteid 站点id
     */
    public function account_LoseEfficacy(){
        $uid=is_numeric($_POST['uid'])?$_POST['uid']:0;
        $siteid=is_numeric($_POST['siteid'])?$_POST['siteid']:0;
        $type=!empty($_POST['type'])?$_POST['type']:0;
        if(!empty($uid) && !empty($siteid)){
            $model = M('', '', C('flashSale'));
            $updatesql="UPDATE f_user_rel SET u_site_status = '3' WHERE u_id = '".$uid."' and site_id = '".$siteid."'";
            $result=$model->execute($updatesql);
            if($type == 1){

            }
            if($result){
                return $this->ajaxReturn(array('code' => 1, 'msg' => "已标注失效", 'data' =>''));
            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "用户标注失效失败", 'data' =>$updatesql));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "用户标注失效参数错误", 'data' =>''));
        }
    }


    /**
     *定时任务创建主机接口
    */
    public function createHost(){
        $taskrelid=is_numeric($_POST['task_relid'])?$_POST['task_relid']:'';
        $tasktype=htmlspecialchars($_POST['tasktype']);
        if($taskrelid){
            $model = M('', '', C('flashSale'));
            $sql="select * from f_task_rel where task_type = '3' and rules like '%\"python\":\"".$tasktype."\"%' and task_relid = ".$taskrelid;
            $result=$model->query($sql)[0];
            if($result){
                $result['rules']=json_decode($result['rules'],true);
                $sqlval='';
                $hostconfig=$result['rules']['hostPackage'];
                switch ($result['rules']['formdata']['serverid']) {
                    case 1:
                        $actiondata = array('Action' => 'CreateInstance', 'ImageId' => $result['rules']['hostPackage']['Img']['img_url'], 'Duration'=>'1H','InstanceType' => $result['rules']['hostPackage']['taocan']['sdktype'], 'InstanceName' => '', 'ExtraExtDisksize' => 0,'AvailabilityZoneId'=>$result['rules']['hostPackage']['taocan']['zoneid']);

                        // $actiondata = array('Action' => 'CreateInstance', 'ImageId' => $resultimg['img_url'], 'Duration'=>'1H','InstanceType' => $packagelist['dataother']['hostsdk'], 'InstanceName' => '', 'ExtraExtDisksize' => 0,'AvailabilityZoneId'=>$AvailabilityZoneId[1]);
                        for ($i = 0; $i < intval($result['rules']['formdata']['hostnumber']); $i++) {
                            //创建主机
                            $actiondata['InstanceName'] = 'qianggou'.$result['t_id'].getorderid();
                            $resultdata = apimeituanyun($result['rules']['services'], $actiondata)['CreateInstanceResponse']['Instance'];
                            //创建浮动ip
                            if (is_array($resultdata) && !empty($resultdata)) {
                                $resultip = apimeituanyun($result['rules']['services'], array('Action'=>'AllocateAddress','Name'=>$actiondata['InstanceName'],'AvailabilityZoneId'=>$result['rules']['hostPackage']['taocan']['zone']))['AllocateAddressResponse']['Address'];
                                file_get_contents('http://http-web.zhimaruanjian.com/index/index/save_white?neek=23963&appkey=13fc3d9d792df9cd5a99f39811a798e6&spec=yangsheng9527&white='.$resultip['publicIp']);
                                $ipid=$resultip['allocationId'];
                                $ipadress=$resultip['publicIp'];
                                $hostconfig['instanceType'] = $resultdata['instanceType'];
                                $hostconfig['ip']=$ipadress;
                                $hostconfig['ipid']=$ipid;
                                $hostconfig['linkExtranet']='0';
                                $hostconfig['secGroupId'] = $resultdata['secGroupId'];
                                $hostconfig['volume'] = $resultdata['volume'];
                                if ($i == 0) {
                                    $sqlval = "('" . $result['t_id'] . "','" . $resultdata['instanceName'] . "','" . $resultdata['instanceId'] . "','" . json_encode($hostconfig, JSON_UNESCAPED_UNICODE) . "','" . strtotime($resultdata['createdAt']) . "','" . $result['rules']['hostPackage']['Img']['img_name'] . "','" . $result['rules']['formdata']['serverid'] . "')";
                                } else {
                                    $sqlval .= ",('" .$result['t_id'] . "','" . $resultdata['instanceName'] . "','" . $resultdata['instanceId'] . "','" . json_encode($hostconfig, JSON_UNESCAPED_UNICODE) . "','" . strtotime($resultdata['createdAt']) . "','" . $result['rules']['hostPackage']['Img']['img_name'] . "','" . $result['rules']['formdata']['serverid'] . "')";
                                }

                            }else{
                                continue;
                            }
                        }
                        break;
                    case 2:
                        $actiondata=array('Version'=>'2017-08-01','InstanceChargeType'=>'POSTPAID_BY_HOUR','Placement.Zone'=>$result['rules']['hostPackage']['taocan']['zone'],'InstanceType'=>$result['rules']['hostPackage']['taocan']['sdktype'],'ImageId'=>$result['rules']['hostPackage']['Img']['img_url'],'InternetAccessible.InternetChargeType'=>'BANDWIDTH_POSTPAID_BY_HOUR','InternetAccessible.InternetMaxBandwidthOut'=>2,'InternetAccessible.PublicIpAssigned'=>'TRUE','InstanceCount'=>intval($result['rules']['formdata']['hostnumber']),'LoginSettings.Password'=>'1q2w3E4R@ls');
                        $result['rules']['services']['model']='cvm';
                        $tencatresult=tencat($result['rules']['services'],'RunInstances',$actiondata);
                        if(isset($tencatresult['Response']['InstanceIdSet']) && !empty($tencatresult['Response']['InstanceIdSet'])){
                            $tencatresult=$tencatresult['Response']['InstanceIdSet'];
                            for ($i = 0; $i < intval($tencatresult); $i++) {
                                $msgdata[] = $tencatresult[$i];
                                $hostconfig['ip']='公网ip';
                                $hostconfig['ipid']='';
                                $hostconfig['linkExtranet']='3';
                                $hostconfig['instanceType'] = $actiondata['instanceType'];
                                $hostconfig['password']='1q2w3E4R@ls';
                                $hostconfig['secGroupId'] = '';
                                $hostconfig['availabilityZoneId'] = $result['rules']['hostPackage']['taocan']['zone'];;
                                $hostconfig['volume'] = '';
                                if ($i == 0) {
                                    $sqlval = "('" .$result['t_id'] . "','" .  $tencatresult[$i] . "','" .  $tencatresult[$i]. "','" . json_encode($hostconfig, JSON_UNESCAPED_UNICODE) . "','" . time() . "','" . $result['rules']['hostPackage']['Img']['img_name'] . "','" . $result['rules']['formdata']['serverid'] . "')";
                                } else {
                                    $sqlval .= ",('" . $result['t_id']. "','" .  $tencatresult[$i] . "','" .  $tencatresult[$i] . "','" . json_encode($hostconfig, JSON_UNESCAPED_UNICODE) . "','" . time() . "','" . $result['rules']['hostPackage']['Img']['img_name'] . "','" . $result['rules']['formdata']['serverid'] . "')";
                                }
                            }
                        }
                        break;
                    case 4:
                        //安全组
                        $actiondata=array('setRegionId'=>$result['rules']['hostPackage']['taocan']['regions']);
                        $resultGetGroupAli = json_decode(json_encode(ali($result['rules']['services'], '\Ecs\Request\V20140526\DescribeSecurityGroupsRequest', $actiondata)),true);//获取组
                        if(empty($resultGetGroupAli['TotalCount'])){
                            //没有组创建组,并设置入网规则
                            $actiondata=array('setRegionId'=>$result['rules']['hostPackage']['taocan']['regions'],'setSecurityGroupName'=>$result['rules']['hostPackage']['taocan']['zone']);
                            $resultali = json_decode(json_encode(ali($result['rules']['services'], '\Ecs\Request\V20140526\CreateSecurityGroupRequest', $actiondata)),true);
                            $groupid=$resultali['SecurityGroupId'];// [SecurityGroupId] => sg-m5egm25gfdxzfgf6kbpl
                            $setgroupdata=array('setSecurityGroupId'=>$groupid,'setSourceCidrIp'=>'0.0.0.0/0','setRegionId'=>$result['rules']['hostPackage']['taocan']['regions'],'setIpProtocol'=>'tcp','setPortRange'=>'3389/3389');
                            ali($result['rules']['services'], '\Ecs\Request\V20140526\AuthorizeSecurityGroupRequest',$setgroupdata);
                            $setgroupdata['setPortRange']='80/80';
                            ali($result['rules']['services'], '\Ecs\Request\V20140526\AuthorizeSecurityGroupRequest',$setgroupdata);
                            $setgroupdata['setPortRange']='80/80';
                            ali($result['rules']['services'], '\Ecs\Request\V20140526\AuthorizeSecurityGroupRequest',$setgroupdata);
                            $setgroupdata['setPortRange']='443/443';
                            ali($result['rules']['services'], '\Ecs\Request\V20140526\AuthorizeSecurityGroupRequest',$setgroupdata);
                            $setgroupdata['setPortRange']='22/22';
                            ali($result['rules']['services'], '\Ecs\Request\V20140526\AuthorizeSecurityGroupRequest',$setgroupdata);
                            $setgroupdata['setIpProtocol']='ICMP';
                            $setgroupdata['setPortRange']='-1/-1';
                           ali($result['rules']['services'], '\Ecs\Request\V20140526\AuthorizeSecurityGroupRequest',$setgroupdata);
                        }else{
                            $groupid=$resultGetGroupAli['SecurityGroups']['SecurityGroup'][0]['SecurityGroupId'];
                        }
                        $createdata=array('setRegionId'=>$result['rules']['hostPackage']['taocan']['regions'],'setZoneId'=>$result['rules']['hostPackage']['taocan']['zoneid'],'setImageId'=>$result['rules']['hostPackage']['Img']['img_url'],'setInstanceType'=>$result['rules']['hostPackage']['taocan']['hostsdk'],'setSecurityGroupId'=>$groupid,'setInstanceName'=>'','setInternetChargeType'=>'PayByBandwidth','setInternetMaxBandwidthIn'=>2,'setInternetMaxBandwidthOut'=>2,'setPassword'=>'1q2w@3E4R');
                        for ($i = 0; $i < intval($result['rules']['formdata']['hostnumber']); $i++) {
                            $createdata['setInstanceName'] = 'qianggou'.$result['t_id'].getorderid();
                            $resultCreateAli = json_decode(json_encode(ali($result['rules']['services'], '\Ecs\Request\V20140526\CreateInstanceRequest', $createdata)),true);//创建主机
                            if(isset($resultCreateAli['InstanceId']) && !empty($resultCreateAli['InstanceId'])) {
                                //分配公网ip
                                $resultipAli = json_decode(json_encode(ali($result['rules']['services'], '\Ecs\Request\V20140526\AllocatePublicIpAddressRequest', array('setInstanceId'=>$resultCreateAli['InstanceId']))),true);
                                //启动实例
                                ali($result['rules']['services'], '\Ecs\Request\V20140526\StartInstanceRequest', array('setInstanceId'=>$resultCreateAli['InstanceId']));
                                $hostconfig['instanceType'] = $createdata['setInstanceType'];
                                $hostconfig['ip']=$resultipAli['IpAddress'];
                                $hostconfig['ipid']='';
                                $hostconfig['password']='1q2w@3E4R';
                                $hostconfig['linkExtranet']=1;
                                $hostconfig['secGroupId'] = $groupid;
                                $hostconfig['availabilityZoneId'] = $result['rules']['hostPackage']['taocan']['zone'];
                                $hostconfig['volume'] = '';
                                if ($i == 0) {
                                    $sqlval = "('" . $result['t_id'] . "','" . $actiondata['setInstanceName'] . "','" .$resultCreateAli['InstanceId'] . "','" . json_encode($hostconfig, JSON_UNESCAPED_UNICODE) . "','" . time() . "','" . $result['rules']['hostPackage']['Img']['img_name'] . "','" . $result['rules']['services']['serverid'] . "')";
                                } else {
                                    $sqlval .= ",('" . $result['t_id']. "','" . $actiondata['InstanceName'] . "','" .$resultCreateAli['InstanceId'] . "','" . json_encode($hostconfig, JSON_UNESCAPED_UNICODE) . "','" . time() . "','" . $result['rules']['hostPackage']['Img']['img_name'] . "','" . $result['rules']['services']['serverid'] . "')";
                                }
                            }
                        }
                        break;
                    default :
                        break;
                }
                if(!empty($sqlval)) {
                    $sql = "insert IGNORE into f_team_host(t_id,host_name,host_unionid,host_config,host_createtime,img_name,host_type) values " . $sqlval . " ";
                    $resultsql = $model->execute($sql);
                    $msg = $resultsql > 0 ? "添加成功" : "添加失败";
                }else{
                    $resultsql=0;$msg="添加失败";
                }
                if ($resultsql > 0) {
                    return $this->ajaxReturn(array('code' => 1, 'msg' => $msg, 'data' =>$msgdata));
                } else {
                    return $this->ajaxReturn(array('code' => 4001, 'msg' => $msg, 'data' =>''));
                }

            }else{
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "该类型任务不存在", 'data' =>''));
            }
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "时间错误", 'data' =>''));
        }
    }


    /**
     * 删除定时任务
    */
    public function deleteTimeTask(){
        $sql="delete from f_task_rel where task_type = '3' and rules like '%\"python\":\"".$tasktype."\"%' and task_relid = ".$taskrelid;
    }

    /**
     * 获取失效账号
    */
    public function checkaccount(){
        $tid=is_numeric($_POST['tid'])?$_POST['tid']:'';
        $model = M('', '', C('flashSale'));
        $orderbyarray=array('ORDER BY a.mobile asc','ORDER BY a.mobile desc','ORDER BY a.u_id asc','ORDER BY a.u_id desc','ORDER BY a.create_time asc','ORDER BY a.create_time desc');
        $orderby=$orderbyarray[array_rand($orderbyarray,1)];
        $sql='SELECT a.u_id,a.u_eamil,a.u_pwd FROM f_user AS a INNER JOIN f_user_rel AS d ON a.u_id = d.u_id WHERE a.t_id = '.$tid.' and d.u_site_status = 3 and d.u_site_task_status =1 '.$orderby.' limit 1';
        $result=$model->query($sql);
        if($result){
           M('','',C('flashSale'))->execute("update f_user_rel set u_site_task_status=2 where u_id = ".$result[0]['u_id']." ");
            return $this->ajaxReturn(array('code' => 1, 'msg' => "失效账号获取成功", 'data' =>$result));
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "你的团队账号很健康", 'data' =>''));
        }
    }

    /**
     * 失效账号可以登陆修改为正常账号
    */
    public function updateCheckAccount(){
        $u_id=is_numeric($_POST['uid'])?$_POST['uid']:'';
        $result=M('','',C('flashSale'))->execute("update f_user_rel set u_site_status=1 where u_id = ".$u_id." ");
        if($result){
            return $this->ajaxReturn(array('code' => 1, 'msg' => "账号恢复成功", 'data' =>''));
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "恢复失败", 'data' =>''));
        }
    }

    /**
     * 获取锁定账号
    */
    public function findonelockaccount(){

    }


    public function deleteCheckAccount(){
        $u_id=is_numeric($_POST['uid'])?$_POST['uid']:'';
        $result=M('','',C('flashSale'))->execute("DELETE f_user,f_user_rel from f_user LEFT JOIN f_user_rel ON f_user.u_id=f_user_rel.u_id WHERE f_user.u_id=$u_id");
        if($result){
            return $this->ajaxReturn(array('code' => 1, 'msg' => "账号删除成功", 'data' =>''));
        }else{
            return $this->ajaxReturn(array('code' => 4001, 'msg' => "账号删除失败", 'data' =>''));
        }
    }






}
